package cn.virens.main;

import java.lang.management.ManagementFactory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.virens.main.cmpt.Component;
import cn.virens.main.cmpt.ComponentRegistry;
import cn.virens.main.timer.TimedTaskRegistry;

public abstract class AppLoad implements Component {
	protected static final Logger logger = LoggerFactory.getLogger(AppLoad.class);

	private static final TimedTaskRegistry regtimer = new TimedTaskRegistry();
	private static final ComponentRegistry regcmpt = new ComponentRegistry();

	private static final AppConfig setting = AppConfigImpl.of("config.setting");
	private static final Runtime runtime = Runtime.getRuntime();

	protected static <T extends AppLoad> void load(T application) throws Exception {
		logger.debug("The Server starting...");

		// 绑定应用退出钩子
		runtime.addShutdownHook(new Thread(() -> {
			try {
				logger.debug("The Server stoping...");

				// 组件销毁
				regtimer.destroy();
				regcmpt.destroy();

				logger.debug("Stop App...");

				// 执行应用销毁
				application.destroy();
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			} finally {
				logger.debug("The Server stoped.");
			}
		}));

		logger.debug("Load App...");

		// 启动应用
		application.start(regcmpt, regtimer);
		application.initialize(setting);

		// 组件初始化
		regcmpt.initialize(setting);
		regtimer.initialize(setting);

		// 获取应用运行信息
		String runInf = ManagementFactory.getRuntimeMXBean().getName();
		String[] runInfo = runInf.split("@", 2);

		logger.debug("The Server pid:" + runInfo[0]);
		logger.debug("The Server pkg:" + runInfo[1]);
		logger.debug("The Server started.");
		logger.debug("The Server runing...");
	}

	/**
	 * 应用启动
	 * 
	 * @param regcmpt  组件注册器
	 * @param regtimer 定时器注册器
	 */
	protected abstract void start(ComponentRegistry regcmpt, TimedTaskRegistry regtimer);
}
